package com.example.redis.mqtt;

import com.example.redis.constant.CommonConstant;
import com.example.redis.redis.RedisStringUtil;
import io.lettuce.core.RedisConnectionException;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class MqttCallBackHandler implements MqttCallback {

    private MqttSubClient client;
    private RedisStringUtil redisStringUtil;
    @Autowired
    @Lazy
    public MqttCallBackHandler(MqttSubClient client,RedisStringUtil redisStringUtil){
        this.client=client;
        this.redisStringUtil=redisStringUtil;
    }

    /**
     * 断开连接后回调方法
     */
    @Override
    public void connectionLost(Throwable throwable) {

        log.info("======MQTT连接断开=====");

        //重新订阅主题
        client.subscribe();
        log.info("=====MQTT重联成功=====");


    }


    /**
     * 接收订阅到的消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage message)  {
        // info信息记得去掉避免产生过多日志
//        log.info("=====MQTT消息订阅成功=====");
        String IMEI=topic.substring(5,topic.length()-3);
//        log.info("MQTT收到IMEI: {}", IMEI);

        //todo 消息处理 将设备传入redis，注意是否需要使用多线程
        try{
            deviceLoginRedis(CommonConstant.REDIS_PREFIX+IMEI,IMEI, CommonConstant.EXPIRE_SECONDS, TimeUnit.SECONDS);
        }catch (RedisConnectionFailureException e){
            log.error("redis connection failed, imei:{}",IMEI);
        }
        catch(Exception e){
            log.error("login redis error!",e);
        }


    }
    private void deviceLoginRedis(String key, String value, long timeout, TimeUnit timeUnit){
        Boolean alreadyLogin=redisStringUtil.hasKey(key);
        if(alreadyLogin==null){
            return ;
        }
        // 未登录则登录
        if(!alreadyLogin){
            redisStringUtil.setValue(key,value,timeout,timeUnit);
//            System.out.println(key+" login"+" TTL:"+redisStringUtil.getExpire(key, timeUnit));
        } else{
            long before=redisStringUtil.getExpire(key, timeUnit);
            redisStringUtil.expire(key,timeout,timeUnit);
//            System.out.println(key+" refresh before:"+before+" after:"+redisStringUtil.getExpire(key, timeUnit));
        }
    }

    /**
     * 发送完成
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        //Deprecated
        log.info("=====MQTT消息发送完毕=====");
    }
}
